import 'dart:async';

import 'package:get/get.dart';
import 'package:xuance/bean/GlobalType.dart';
import 'package:xuance/bean/ReceiveDatabean.dart';
import 'package:xuance/bean/TimeEnum.dart';
import 'package:xuance/bean/global_event_bean.dart';
import 'package:xuance/main.dart';
import 'package:xuance/network/api/SplunkApi.dart';
import 'package:xuance/util/toast_util.dart';

import 'state.dart';

class SplunkDetailLogic extends GetxController {
  final SplunkDetailState state = SplunkDetailState();
  late String id;
  var queryCondition = "".obs;
  var dateType = TimeEnum.month.obs;
  var page = 1.obs;

  StreamSubscription<GlobalEventBean>? listener;

  @override
  void onInit() {
    super.onInit();
    id = Get.arguments['id'] as String;
    queryCondition.value = Get.arguments['queryCondition'] as String;
    dateType.value = Get.arguments['dateType'] as TimeEnum;

    listener = eventBus.on<GlobalEventBean>().listen((event) {
      if (event.type == GlobalType.updateDate) {
        var bean = event.data as ReceiveDataBean;
        dateType.value = bean.time;
        queryCondition.value = bean.txt;
        getData();
      }
    });

    getData();
  }

  Future<void> getData() async {
    try {
      var bean = await SplunkApi.getListById(
          id: id, page: page.value, queryCondition: queryCondition.value);
      state.list.clear();
      state.list.addAll(bean?.list ?? []);
      page.value = bean?.pageNum?.toInt() ?? 0;
      state.pages.value = bean?.pages?.toInt() ?? 0;
    } catch (e) {
      print("获取splunk 详情列表失败");
    }
  }

  void nextPage() {
    if (page.value < state.pages.value) {
      page++;
      getData();
    } else {
      showToast("已经是最后一页");
    }
  }

  void lastPage() {
    if (page.value == 1) {
      showToast("已经是第一页");
    } else {
      page--;
      getData();
    }
  }

  @override
  void onClose() {
    super.onClose();
    listener?.cancel();
  }
}
